package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.util.HttpClient;
import com.atguigu.gmall.payment.service.WxPayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/15 10:29 星期六
 * description:
 */
@Service
public class WxPayServiceImpl implements WxPayService {

    @Value("${weixin.pay.appid}")
    private String appId;

    @Value("${weixin.pay.partner}")
    private String partner;

    @Value("${weixin.pay.partnerkey}")
    private String partnerKey;

    @Value("${weixin.pay.notifyUrl}")
    private String notifyUrl;

    /**
     * 获取微信支付的二维码地址
     *  @param payMap    订单描述
     * @return
     */
    @Override
    public Map<String, String> getPayCodeUrl(Map<String, String> payMap) {

        //参数校验
        if(StringUtils.isEmpty(payMap.get("body")) ||
                StringUtils.isEmpty(payMap.get("orderId")) ||
                StringUtils.isEmpty(payMap.get("money"))){
            throw new RuntimeException("参数错误");
        }

        try {
            //包装请求参数
            Map<String, String> param = new HashMap<>();
            param.put("appid",appId);
            param.put("mch_id",partner);
            param.put("nonce_str", WXPayUtil.generateNonceStr());
            param.put("body",payMap.get("body"));
            param.put("out_trade_no",payMap.get("orderId"));
            param.put("total_fee",payMap.get("money"));
            param.put("spbill_create_ip","192.168.200.1");
            param.put("notify_url",notifyUrl);
            param.put("trade_type","NATIVE");
            //包装附加参数
            Map<String,String> attach = new HashMap<>();
            attach.put("exchange", payMap.get("exchange"));
            attach.put("routingKey", payMap.get("routingKey"));
            if(!StringUtils.isEmpty(payMap.get("username"))){
                attach.put("username", payMap.get("username"));
            }
            //存储附加参数
            param.put("attach", JSONObject.toJSONString(attach));
            //将map转换为xml同时生成签名
            String xmlParam = WXPayUtil.generateSignedXml(param, partnerKey);
            //请求微信支付统一下单api的url,发送post请求
            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            HttpClient httpClient = new HttpClient(url);
            httpClient.setXmlParam(xmlParam);
            httpClient.setHttps(true);
            //请求发送
            httpClient.post();
            //获取返回结果 :xml格式的字符串
            String content = httpClient.getContent();
            //解析返回结果,判断通信标识和业务标识
            Map<String, String> result = WXPayUtil.xmlToMap(content);
            //若都为success,返回二维码地址
            if(result.get("return_code").equals("SUCCESS") &&
                    result.get("result_code").equals("SUCCESS")){
                return result;
            }else{
                //否则返回错误的原因
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据订单号查询订单的支付结果
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> getPayResult(String orderId) {

        //参数校验
        if(StringUtils.isEmpty(orderId)){
            throw new RuntimeException("参数错误");
        }

        try {
            //包装请求参数
            Map<String, String> param = new HashMap<>();
            param.put("appid",appId);
            param.put("mch_id",partner);
            param.put("nonce_str", WXPayUtil.generateNonceStr());
            param.put("out_trade_no",orderId);
            //将map转换为xml同时生成签名
            String xmlParam = WXPayUtil.generateSignedXml(param, partnerKey);
            //请求微信支付统一下单api的url,发送post请求
            String url = "https://api.mch.weixin.qq.com/pay/orderquery";
            HttpClient httpClient = new HttpClient(url);
            httpClient.setXmlParam(xmlParam);
            httpClient.setHttps(true);
            //请求发送
            httpClient.post();
            //获取返回结果 :xml格式的字符串
            String content = httpClient.getContent();
            //解析返回结果,判断通信标识和业务标识
            Map<String, String> result = WXPayUtil.xmlToMap(content);
            //若都为success,返回二维码地址
            if(result.get("return_code").equals("SUCCESS") &&
                    result.get("result_code").equals("SUCCESS")){
                return result;
            }else{
                //否则返回错误的原因
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
